<?php
namespace yan\jwt\factory;
use Yii;
use ExpiredException;
use phpseclib3\Crypt\AES;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Math\BigInteger;
use yan\jwt\jwt\Key;
class JwtVerify extends \yan\jwt\AbstractFactory{
	public $environment;
	private $jwt;

	function build($environment)
    {
        $this->environment = $environment;
        $this->jwt = \yan\jwt\jwt\Jwt::instance();
        $this->init();
        return $this;
    }
    public function init(){

    }
	public function run($data=[]){
		
        $idToken = $data['code'];
        $key = $data['key']??$this->environment->getPublicKey();
		
        try {
            $payload = $this->jwt->decode($idToken, $key);
            if(empty($payload)){
                return false;
            }
            return (array)$payload;
        } catch (ExpiredException $e) { // @phpstan-ignore-line
            return false;
        } catch (\Exception $e) {
            // continue
            // var_dump($e->getMessage());
            return false;
        }
	}
	
	public function retrieveCertsFromLocation(){
		if(($data = Yii::$app->cache->get('google_cert'))===false){
			$data = $this->curl->build(self::FEDERATED_SIGNON_CERT_URL)->run();
			Yii::$app->cache->set('google_cert', $data);
		}		
		return json_decode($data, true);
	}

	private function getPublicKey($cert)
    {
        $modulus = new BigInteger($this->jwt->urlsafeB64Decode($cert['n']), 256);
        $exponent = new BigInteger($this->jwt->urlsafeB64Decode($cert['e']), 256);
        $component = ['n' => $modulus, 'e' => $exponent];

        $loader = PublicKeyLoader::load($component);

        return $loader->toString('PKCS8');
    }
}